package workspace.teaweb.User.service.impl;


import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import springfox.documentation.annotations.ApiIgnore;
import workspace.teaweb.User.mappers.UserMapper;
import workspace.teaweb.User.pojo.dto.UserLoginParam;
import workspace.teaweb.User.pojo.dto.UserSaveParam;
import workspace.teaweb.User.pojo.entity.User;
import workspace.teaweb.User.pojo.vo.UserVO;
import workspace.teaweb.User.service.UserService;
import workspace.teaweb.base.exception.ServiceException;
import workspace.teaweb.base.response.StatusCode;

import javax.servlet.http.HttpSession;
import java.util.Date;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public void saveUser(UserSaveParam userSaveParam) {
        log.debug("注册用户业务:{}",userSaveParam);
        User user = new User();
        BeanUtils.copyProperties(userSaveParam,user);
        user.setIsAdmin(false);//默认新注册的是用户, true是商户
        user.setCreateTime(new Date());
        userMapper.insert(user);
    }

    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        log.debug("用户登录业务:{}",userLoginParam);
        UserVO userVO = userMapper.selectByUsername(userLoginParam.getUsername());//根据前端的用户名查数据库中是否有该用户

        if(userVO==null){//用户名不存在
            throw new ServiceException(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        //   ↓  查询用户输入的密码是否和数据库中该用户名的密码相同
        if (!userVO.getPassword().equals(userLoginParam.getPassword())){//密码错误
            throw new ServiceException(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        log.debug("用户查询结果:{}",userVO);
        return userVO;
    }


    @Override
    public void updateUser(UserSaveParam userSaveParam) {
        log.debug("更新/修改用户业务:{}",userSaveParam);
        User user = new User();
        BeanUtils.copyProperties(userSaveParam,user);
        user.setUpdateTime(new Date());
        userMapper.update(user);
    }



    // 下面的方法用来获取当前登录用户
    //获取登录用户的id,username,password......
    @Override
    public UserVO getCurrentUser(HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        // {"state":2000,message:"操作成功",data:null}
        // {"state":2000,message:"操作成功",data:userVO的展开}
        return userVO;
    }

    // 下面方法获取当前登录用户的id
    // 获取登录用户的id
    @Override
    public Long getCurrentUserId(HttpSession session) {
        UserVO userVO = getCurrentUser(session);
        return userVO != null ? userVO.getId() : null;
    }




}
